package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentRepository;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class IStrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private StrategyCommentRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(StrategyComment strategyComment) {
        strategyComment.setCreateTime( new Date() );
        repository.save( strategyComment );
    }

    @Override
    public Page <StrategyComment> query(StrategyCommentQuery qo) {
        Query query = new Query();
        query.addCriteria( Criteria.where( "detailId" ).is( qo.getDetailId() ) );
        //查count
        long total = template.count( query, StrategyComment.class );
        if (total == 0) {
            return Page.empty();
        }
        //查list
        //添加分页
        Pageable pageable = PageRequest.of( qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "createTime" );
        query.with( pageable );
        List <StrategyComment> strategyComments = template.find( query, StrategyComment.class );
        return new PageImpl <>( strategyComments, pageable, total );
    }

    @Override
    public void  commentThumbUp(String toid, Long fromid) {
        //判断是不是点赞,toid是当前评论的id
        StrategyComment comment = template.findById( toid, StrategyComment.class );
        List <Long> thumbuplist = comment.getThumbuplist();
        if (!thumbuplist.contains( fromid )) {
            //是点赞
            thumbuplist.add( fromid );
            comment.setThumbupnum( comment.getThumbupnum() + 1 );

        } else {
            //取消点赞
            thumbuplist.remove( fromid );
            comment.setThumbupnum( comment.getThumbupnum() -1 );
        }
        repository.save( comment );
    }


}
